import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image, Swiper, SwiperItem  , Picker } from '@tarojs/components';
import { baseImgSrc , baseTxKey} from '../../util/base_url';
import QQMapWX from '../../util/qqmap-wx-jssdk.min.js';
import { AtButton , AtMessage } from 'taro-ui';
import { getBanner , getUserOrderStatus , getUpHide , getadvMain} from '../../util/api';
import { singCheckCancle , toLogin  , toWaitOrder , handerTree } from '../../util/util';
import { getGlobalData , setGlobalData , getToken , getRole } from '../../util/globaldata';
import './tabmain.scss';

export default class TabMain extends Component {
    config = {
        navigationBarTitleText: "",
    }
    constructor() {
        super(...arguments);
        this.state = {
            bannerList:[],
            gearList:[{name:"手动挡",status:false,value:0},{name:"自动挡",status:false,value:1}],
            userRole:2,
            isLogin:false,
            selector:[],
            selectorChecked:[0,0,0],
            startAddress:{
                address:"",
                latitude:undefined,
                longitude:undefined,
            },
            endAddress:{
                address:"",
                latitude:undefined,
                longitude:undefined,
            },
            startTime:"",
            navHeight:getGlobalData('navHeight'),
            city:"获取位置中",
            btnStatus:1, //下一步按钮的状态，1还是没有订单  0是等待接单   2是已结单正在进行
            isUp:0, //是否是上架状态  1是限制 0不限制
            advSrc:"",
        }
    }
    config = {
        navigationStyle:'custom',
    }
    componentDidShow() {
        getUserOrderStatus({},true).then( res => {
            this.setState({btnStatus:res.code})
        })
        this.setState({
            userRole:getRole(),
            isLogin:getToken() != null
        },() => {
             
        })
    }
    componentWillMount(){
        getBanner({cid:2}).then(res => {
            if(res.code == 0){
                this.setState({bannerList:res.list});
            }
        })
        getUpHide({},true).then( res => {
            if(res.code == 0){
                this.setState({
                    isUp:res.close,
                },() => {
                    this.getLocalAddress();
                })
            }
        })
        this.initDate();
        Taro.eventCenter.on('successPay',() => {
            this.setState({timeDefault:true,startTime:"",endAddress:{address:"",latitude:undefined,longitude:undefined}})
        })
        getadvMain({},true).then( res => {
            if(res.code == 0){
                this.setState({
                    advSrc:res.list.pic,
                })
            }
        })
    }
    toSuggest(){
        let { isLogin } = this.state;
        if(!isLogin){
            toLogin();
            return false
        }
        wx.navigateTo({
            url:"/pages/suggest/suggest"
        })
    }
    getLocalAddress(){ //坐标转汉字
        let _this = this;
        _this.qqmapsdk = new QQMapWX({
            key: baseTxKey,
        });
        _this.qqmapsdk.reverseGeocoder({
            success: function(res) {//成功后的回调
                let { startAddress , isUp } = _this.state;
                startAddress.address = res.result.address;
                if(res.result.address.indexOf('北京') == -1 && isUp == 1){
                    startAddress = { address:"",latitude:undefined,longitude:undefined,}
                }
                _this.setState({
                    startAddress,
                    city:res.result.address_component.city,
                })
            },
            fail: function(error) {
                _this.setState({
                    city:'定位失败', 
                })
            },
        })
        Taro.getLocation({
            type: 'gcj02',
            success: function (res) {
                let { startAddress , isUp } = _this.state;
                startAddress.latitude = res.latitude;
                startAddress.longitude = res.longitude;
                if(startAddress.address.indexOf('北京') == -1 && isUp == 1){
                    startAddress = { address:"",latitude:undefined,longitude:undefined,}
                    return false
                }
                _this.setState({startAddress:startAddress})
            }
        }) 
    }
    //日期部分功能JS
    initDate(){
        this.setState({
            selector:handerTree([0,0,0]),
            startTime:""
        })
    }
    onChange(e){
        let {  selector , selectorChecked } = this.state;
        selectorChecked = e.detail.value;
        this.setState({
            startTime:`${selector[0][selectorChecked[0]]}${selector[1][selectorChecked[1]]}${selector[2][selectorChecked[2]]}`,
            selectorChecked,
        })
    }
    columnChange(event){
        let {  selectorChecked } = this.state;
        let column = event.detail.column;
        let idx = event.detail.value;
        selectorChecked[column] = idx;
        if(column == 0){
            selectorChecked[1] = 0;
            selectorChecked[2] = 0;
        }else if(column == 1){ 
            selectorChecked[2] = 0;
        }
        this.setState({
            selectorChecked:selectorChecked,
            selector:handerTree(selectorChecked), 
        })
    }
    //档位切换
    changeGear(idx){
        this.setState({
            gearList:singCheckCancle(this.state.gearList,idx)
        })
    }
    //下单
    nextTip(){ 
        let { isLogin , startAddress , endAddress , gearList , startTime} = this.state;
        if(!isLogin){
            toLogin();
            return false
        }
        if(startAddress.address == ''){
            Taro.showToast({title:"请选择出发地",icon:"none"})
            return false
        }
        if(endAddress.address == ''){
            Taro.showToast({title:"请选择目的地",icon:"none"})
            return false
        }
        if(startTime == ''){
            Taro.showToast({title:"请选择开始时间",icon:"none"})
            return false 
        }
        if(gearList.filter(v => v.status).length == 0 ){
            Taro.showToast({title:"请选择档位",icon:"none"})
            return false
        }
        //生成订单基本信息
        let orderInfo = {
            startAddress,
            endAddress,
            start_time:startTime,
            is_dang:gearList.filter(v => v.status),
            car_id:"", 
        }
        setGlobalData('orderInfo',orderInfo);
        Taro.navigateTo({
            url:"/pages/loginRole/loginRole",
        })
    }
    //选择常用地址
    toOftAddress(){
        let { isLogin , } = this.state;
        if(!isLogin){
            toLogin();
            return false
        }
        Taro.eventCenter.on('addressSelect',(startAddress,endAddress) => {
            this.setState({startAddress,endAddress})
        })
        Taro.navigateTo({
            url:"/pages/oftenaddress/oftenaddress",
        })
    }
    //选择地址
    toMapSelect(iden){
        let { startAddress , endAddress , isUp } = this.state;
        let _this = this;
        if(iden == 1 ){ //开始地址
            wx.chooseLocation({
                latitude:startAddress.latitude,
                longitude:startAddress.longitude,
                success(res){
                    if(res.address.indexOf('北京') == -1 && isUp == 1){
                        wx.showToast({title:"目前只开通了北京地区，敬请期待！",icon:"none"})
                        return false
                    }
                    _this.setState({startAddress:{
                        address:res.name,
                        latitude:res.latitude,
                        longitude:res.longitude,
                    }})
                }
            })
        }else{
    
            wx.chooseLocation({
                latitude:endAddress.latitude,
                longitude:endAddress.longitude,
                success(res){ 
                    console.log(res)
                    if(res.address.indexOf('北京') == -1 && isUp == 1){
                        wx.showToast({title:"目前只开通了北京地区，敬请期待！",icon:"none"})
                        return false
                    }
                    _this.setState({endAddress:{
                        address:res.name,
                        latitude:res.latitude,
                        longitude:res.longitude,
                    }})
                }
            })
        }
    }
    //订单列表
    toOrderList(){
        let { btnStatus } = this.state;
        let type = 1;
        if(btnStatus == 0){
            type = 1;
        }else if(btnStatus == 2){
            type = 2;
        }else if(btnStatus == 3){
            type = 3;
        }
        Taro.navigateTo({url:"/pages/orderlist/orderlist?type="+type})
    }
    render() {
        let { bannerList , gearList , startAddress , endAddress  , selectorChecked , navHeight , city , btnStatus , timeOpen , advSrc} = this.state;
        const containerStyle = {
            paddingTop: navHeight + 50 + 'px'
        }
        const navStyle = {
            height: 50 + navHeight + 'px',
            paddingTop: navHeight + 'px'
        }
        return (
            <View className='tabmain' style={containerStyle}>
                <View className='navBar flex align-items flex-start' style={navStyle}>
                    <View>
                        <Text className='iconfont iconlocation'></Text>
                        <Text className='bar-txt'>{city}</Text>
                    </View>
                </View>
                <View className='index-card'>
                    <View className='address'>
                        <View className='item flex align-items space-between' onClick={this.toMapSelect.bind(this,1)}>
                            <Image className='address-image' src={`${baseImgSrc}/address_fa.png`} />
                            {
                                startAddress.address == '' ? (
                                    <Text className='flex1 item-txt flex align-items flex-start'>请设置出发地</Text>
                                ) : (<Text className='flex1 item-txt active flex align-items flex-start'>{startAddress.address}</Text>)
                            }
                        </View>
                        <View className='item flex align-items space-between' onClick={this.toMapSelect.bind(this,2)}>
                            <Image className='address-image' src={`${baseImgSrc}/address_dao.png`} />
                            {
                                endAddress.address == '' ? (
                                    <Text className='flex1 item-txt flex align-items flex-start'>请设置目的地</Text>
                                ) : (<Text className='flex1 item-txt active flex align-items flex-start'>{endAddress.address}</Text>)
                            }
                        </View>
                    </View>
                    <View className='often-address fn-ctr' onClick={this.toOftAddress.bind(this)}>
                        <Text className='often-txt'>从常用路线里选择</Text>
                        <Image className='often-image' src={`${baseImgSrc}/arrow_right.png`} />
                    </View>
                    <View className='start-time flex align-items'>
                        <Image className='left' src={`${baseImgSrc}/index_time.png`} />
                        <Picker className='right flex1 ' mode='multiSelector' range={this.state.selector} 
                        onChange={this.onChange}
                        onColumnChange={this.columnChange.bind(this)}
                        value={this.state.selectorChecked}>
                            <View className='picker-box flex align-items space-between'>
                                {
                                    startTime == ""  ? 
                                       <Text className='right-txt'>出发时间: 请选择</Text> 
                                           : <Text className='right-txt'>出发时间: {startTime}</Text>
                                }
                                <Text className='iconfont iconarrow-right'></Text>
                            </View>
                        </Picker>
                    </View> 
                    <View className='title'>注意事项</View>
                    <View class='flex align-items flex-start'>
                    {
                        gearList.map( (v,idx) => (
                            <View className='gearitem flex align-items space-between' onClick={this.changeGear.bind(this,idx)}>
                                <View className='left'>
                                    {
                                        v.status ? (
                                            <Image className='left-image' src={`${baseImgSrc}/check.png`} />
                                        ) : (
                                            <Image className='left-image' src={`${baseImgSrc}/no_check.png`} />
                                        )
                                    }
                                </View>
                                <View className='right flex1'>{v.name}</View>
                            </View>
                        ))
                    }
                    </View>
                </View>
                <Swiper
                    className='banner'
                    indicatorColor='#999'
                    indicatorActiveColor='#45A065'
                    circular
                    indicatorDots
                    autoplay>
                    {
                        bannerList.map( (v,i) => (
                            <SwiperItem>
                                <Image className='index-banner' src={v.pic} />
                            </SwiperItem>
                        ))
                    }
                </Swiper>
                {
                     btnStatus == 1 ? (
                        <AtButton className='next-tip' type='primary' size='normal' onClick={this.nextTip.bind(this)}>下一步</AtButton>
                    ) : (
                        <AtButton className='next-tip' type='primary' size='normal' onClick={this.toOrderList.bind(this)}>查看正在进行订单</AtButton>
                    )
                }
                <Image className='advsug' src={advSrc} onClick={this.toSuggest.bind(this)} />
                <AtMessage />
            </View>
        )
    }
}
